/**
 * HTTP请求
 * @params url 访问请求的地址
 * @params params 携带的参数
 * @params successFun 访问成功回调函数
 * @params errorFun 访问失败回调函数
 * @params beforeFun 访问之前回调函数
 * @params complete 访问完成回调函数
 * @returns {{httpSendByJsonNoSuffix: Function, httpSendByJsonAndSuffix: Function,
 * httpSendByJsonpNoSuffix: Function, httpSendByJsonpAndSuffix: Function,
 * generalHttpSendNoSuffix: Function, generalHttpSendAndSuffix: Function,
 * getHtmlFile: Function, fileUpload: Function}}
 * @return httpSendByJsonNoSuffix 发送JSON格式请求，不需要加后缀名
 * @return httpSendByJsonAndSuffix 发送JSON格式请求，自定义后缀名
 * @return httpSendByJsonpNoSuffix 发送JSONP格式请求，不需要加后缀名
 * @return httpSendByJsonpAndSuffix 发送JSONP格式请求，自定义后缀名
 * @return generalHttpSendNoSuffix 发送通用格式请求，不需要加后缀名
 * @return generalHttpSendAndSuffix 发送通用格式请求，自定义后缀名
 * @return getHtmlFile 发送HTML文件请求
 * @return fileUpload 上传文件，原生form
 */
function httpUtil() {
	var project_path = '../'; // 项目路径，不填则为相对路径
	var suffixJSON = '.do'; // JSON，URL后缀
	var suffixJSONP = '.do'; // JSONP，URL后缀
	var suffixGeneral = '.do'; // General，URL后缀
	var suffixFileUpload = '.do'; // fileUpload，URL后缀
	var httpUtilFun = {
		httpSendByJsonNoSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url + suffixJSON;
			jQueryAjaxSubmitByJson(url, params, successFun, errorFun, beforeFun, complete);
		},
		httpSendByJsonAndSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url;
			jQueryAjaxSubmitByJson(url, params, successFun, errorFun, beforeFun, complete);
		},
		httpSendByJsonpNoSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url + suffixJSONP;
			jQueryAjaxSubmitByJsonp(url, params, successFun, errorFun, beforeFun, complete);
		},
		httpSendByJsonpAndSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url;
			jQueryAjaxSubmitByJsonp(url, params, successFun, errorFun, beforeFun, complete);
		},
		generalHttpSendNoSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url + suffixGeneral;
			jQueryAjaxSubmitByJsonp(url, params, successFun, errorFun, beforeFun, complete);
		},
		generalHttpSendAndSuffix: function(url, params, successFun, errorFun, beforeFun, complete) {
			url = project_path + url;
			jQueryAjaxSubmitByJsonp(url, params, successFun, errorFun, beforeFun, complete);
		},
		getHtmlFile: function(url, successFun, errorFun, beforeFun, complete) {
			url = project_path + url;
			jQueryAjaxGetHtml(url, successFun, errorFun, beforeFun, complete);
		},
		/**
		 * @param url 上传访问的action
		 * @param fileElementId 上传文件标签的id，类型为数组，支持多个文件上传
		 * @param params 上传可以携带的参数
		 * @param successFun 上传成功的回调函数
		 */
		fileUpload: function(url, fileElementId, params, successFun) {
			if($.ajaxFileUpload == undefined || typeof $.ajaxFileUpload != 'function') {
				$.getScript("lib/ajaxfileupload.js", function() { //加载test.js,成功后，并执行回调函数
					console.log("load ajaxfileupload.js");
					ajaxFileUpload();
				});
			} else {
				ajaxFileUpload();
			}

			function ajaxFileUpload() {
				$.ajaxFileUpload({
					url: project_path + url + suffixFileUpload, //用于文件上传的服务器端请求地址
					secureuri: false, //是否需要安全协议，一般设置为false
					fileElementId: fileElementId, //文件上传域的ID
					dataType: 'jsonp', //返回值类型 一般设置为json
					data: params, //自定义参数
					success: function(data, status) { //服务器成功响应处理函数
						successFun(data);
					},
					error: function(data, status, e) { //服务器响应失败处理函数
						alert("提示信息：" + e);
					}
				})
			}
		}
	};
	// 原生jQuery ajax json提交
	function jQueryAjaxSubmitByJson(url, params, successFun, errorFun, beforeFun, completeFun) {
		$.ajax({
			url: url,
			type: 'post', //GET
			async: false, //或false,是否异步
			data: params,
			timeout: 0, //超时时间，0为永不超时
			dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
			contentType: "application/json;charset=UTF-8",
			traditional: true, //加上此参数，可以使用数组传值
			// 发送请求成功执行的方法
			success: function(data, textStatus, jqXHR) {
				if(successFun != undefined && typeof successFun == 'function') {
					successFun(data, textStatus, jqXHR);
				}
			},
			// 发送请求错误执行的方法
			error: function(xhr, textStatus) {
				console.log(xhr);
				console.log(textStatus);
				if(errorFun != undefined && typeof errorFun == 'function') {
					errorFun(xhr, textStatus);
				}
			},
			// 发送请求前执行的方法
			beforeSend: function(xhr) {
				if(beforeFun != undefined && typeof beforeFun == 'function') {
					beforeFun();
				}
			},
			// 发送请求结束执行的方法
			complete: function(XMLHttpRequest, status) {
				if(completeFun != undefined && typeof completeFun == 'function') {
					completeFun();
				}
			}
		})
	}

	// 原生jQuery ajax jsonp提交
	function jQueryAjaxSubmitByJsonp(url, params, successFun, errorFun, beforeFun, completeFun) {
		$.ajax({
			type: "post",
			async: false,
			url: url,
			data: params,
			dataType: "jsonp",
			contentType: "application/json;charset=UTF-8",
			//traditional: true, //  加上此参数，可以使用数组传值
			jsonp: "callback", //传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
			jsonpCallback: "JSON_CALLBACK" + new Date().getTime(), //自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
			success: function(data, textStatus, jqXHR) {
				if(successFun != undefined && typeof successFun == 'function') {
					setTimeout(function() {
						if(data.flag == false && data.msg == "session_out") {
							alertModule().alertMsg("账号在其它地方登录或者长时间未操作强制下线");
							$rootScope.commit('loginOut');
						} else {
							successFun(data, textStatus, jqXHR);
						}
					});
				}
			},
			error: function(xhr, textStatus) {
				console.log(xhr);
				console.log(textStatus);
				if(errorFun != undefined && typeof errorFun == 'function') {
					errorFun(xhr, textStatus);
				}
			},
			// 发送请求前执行的方法
			beforeSend: function(xhr) {
				if(beforeFun != undefined && typeof beforeFun == 'function') {
					beforeFun(xhr);
				}
			},
			// 发送请求结束执行的方法
			complete: function(XMLHttpRequest, status) {
				if(completeFun != undefined && typeof completeFun == 'function') {
					completeFun(XMLHttpRequest, status);
				}
			}
		})
	}

	// 原生jQuery ajax html文件请求
	function jQueryAjaxGetHtml(url, successFun, errorFun, beforeFun, completeFun) {
		$.ajax({
			type: "get",
			url: url,
			dataType: "html",
			success: function(data) {
				successFun(data);
			},
			error: function(xhr, textStatus) {
				console.log(xhr);
				console.log(textStatus);
				if(errorFun != undefined && typeof errorFun == 'function') {
					errorFun(xhr, textStatus);
				}
			},
			// 发送请求前执行的方法
			beforeSend: function(xhr) {
				if(beforeFun != undefined && typeof beforeFun == 'function') {
					beforeFun(xhr);
				}
			},
			// 发送请求结束执行的方法
			complete: function(XMLHttpRequest, status) {
				if(completeFun != undefined && typeof completeFun == 'function') {
					completeFun(XMLHttpRequest, status);
				}
			}
		})
	}

	return httpUtilFun;
}
/**
 * 弹出窗口
 * @params msg 需要显示的信息
 * @params confirmFun 确认窗口，点击确认按钮调用的函数
 * @params cancelFun 确认窗口，点击取消按钮调用的函数
 * @returns {{alertMsg: Function, confirmMsg: Function}}
 * @return alertMsg 弹出信息窗口
 * @return confirmMsg 弹出确认窗口
 */
function alertModule() {
	var alertModuleFun = {
		alertMsg: function(msg) {
			msg = (msg == undefined) ? '' : msg;
			sessionStorage.setItem("alertMsg", msg);
			layer.config({
				extend: '../../../page/modal/modal_alertMsg.css'
			});
			var config = {
				type: 1,
				area: 'auto',
				title: false,
				closeBtn: 0,
				shadeClose: true,
				scrollbar: true,
				skin: 'layer-modal_alertMsg'
			};
			loadComponent().loadHtml('page/modal/modal_alertMsg.html', function(html) {
				config.content = html;
				layer.open(config);
			})
		},
		confirmMsg: function(msg, confirmFun, cancelFun) {
			msg = (msg == undefined) ? '' : msg;
			window.confirmMsg = {
				msg: msg,
				yes: confirmFun,
				no: cancelFun
			};
			layer.config({
				extend: '../../../page/modal/modal_confirmMsg.css'
			});
			var config = {
				type: 1,
				area: 'auto',
				title: false,
				closeBtn: 0,
				shadeClose: true,
				scrollbar: true,
				skin: 'layer-modal_confirmMsg'
			};
			loadComponent().loadHtml('page/modal/modal_confirmMsg.html', function(html) {
				config.content = html;
				window.confirmMsg.index = layer.open(config);
			})
		},
		openModal: function(url, config) {
			loadComponent().loadHtml(url, function(html) {
				config.shadeClose = false;
				config.content = html;
				$rootScope.state.modalIndex.push(layer.open(config));
			})
		},
		closeModal: function() {
			try {
				var closeIndex = $rootScope.state.modalIndex[$rootScope.state.modalIndex.length - 1];
				layer.close(closeIndex);
				$rootScope.state.modalIndex.splice(-1, 1);
			} catch(e) {
				$rootScope.state.modalIndex = [];
			}
		}
	};
	return alertModuleFun;
}
/**
 * 载入文件
 * @returns {{loadHtml: loadHtml, loadJavaScript: loadJavaScript}}
 * @return loadHtml 载入Html页面，返回页面的内容
 * @return loadJavaScript 载入JavaScript文件，返回文件的内容this
 */
function loadComponent() {
	return {
		loadHtml: function(url, successFun) {
			require(['lib/require/text!' + url], function(html) {
				//console.log(html);
				//console.log(this.route);
				successFun(html);
			});
		},
		loadJavaScript: function(url, successFun) {
			require([url], function() {
				//console.log(html);
				//console.log(this.route);
				successFun(this);
			});
		}
	}
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function(fmt) { //author: meizz 
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}